package service;

import bean.AdminBean;
import bean.GeneralBean;
import bean.UserBean;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import dao.AdminDao;
import dao.GeneralDao;
import dao.UserDao;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import tools.UtilMessage;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * @Author 王志康
 * @Date 2021/9/7 14:16
 * @Version 1.0.0
 */
public class AdminService {
    /**
     * 添加新用户
     *
     * @param user 新添加的用户
     */
    public static void addUserService(UserBean user) {
        if (UserDao.verification(user)) {
            UserDao.register(user);
            new UtilMessage().messageShow("添加成功");
        } else {
            new UtilMessage().messageShow("请检查账号和手机");
        }
    }

    /**
     * 添加新管理员
     *
     * @param admin 新添加的管理员
     */
    public static void addAdminService(AdminBean admin) {
        if (AdminDao.verification(admin)) {
            AdminDao.register(admin);
            new UtilMessage().messageShow("添加成功");
        } else {
            new UtilMessage().messageShow("此管理员已存在");
        }
    }

    public static void importDate() {
        FileChooser fileChooser = new FileChooser();
        //设置选择拓展样式
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("表格", "*.xls*")
        );
        //获取桌面地址
        FileSystemView fsv = FileSystemView.getFileSystemView();
        fileChooser.setInitialDirectory(fsv.getHomeDirectory());
        File file = fileChooser.showOpenDialog(new Stage());
        if (file == null) {
            return;
        }
        //调用HuTool中的ExcelUtil工具类读取表格
        ExcelReader reader = ExcelUtil.getReader(file);
        List<List<Object>> readAll = reader.read();
        int sum = 0;
        for (List<Object> read : readAll) {
            //时间转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date;
            try {
                date = sdf.parse(String.valueOf(read.get(4)));
            } catch (ParseException e) {
                continue;
            }
            GeneralBean general = new GeneralBean(Integer.parseInt((String) read.get(0)), (String) read.get(1),
                    Double.parseDouble((String) read.get(2)), Boolean.parseBoolean(String.valueOf(read.get(3))),
                    date, (String) read.get(5), (String) read.get(6));
            if (!GeneralDao.verification((String) read.get(0))) {
                GeneralDao.addItem(general);
                sum = sum + 1;
            }
        }
        new UtilMessage().messageShow("共添加了" + sum + "件商品");
    }
}
